package com.data_structure_algorithm.data_structure.tree.huff;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Authror PABLO
 * @Date 2022/3/31 22:39
 * @Desc 构建赫夫曼树
 */
public class HuffmanCode {
    public static void main(String[] args) {
        int[] arr = {13, 7, 8, 3, 29, 6, 1};
        Nodes huffmanTree = createHuffmanTree(arr);
       preOrder(huffmanTree);

    }

    private static void preOrder(Nodes node) {
        if (node != null) node.preOrder();
        else System.out.println("空树");
    }

    public static Nodes createHuffmanTree(int[] arr) {


        //将数组转为集合
        List<Nodes> list = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            list.add(new Nodes(arr[i]));
        }




        //循环处理集合
        while (list.size() > 1) {  //这里必须>1，因为循环中list.get(1);

            Collections.sort(list);

            //取出前两个元素
            Nodes left = list.get(0);
            Nodes right = list.get(1);

            Nodes root = new Nodes(left.val + right.val);

            root.left = left;

            root.right = right;

            //删除集合对应元素
            list.remove(left);
            list.remove(right);

            //将新节点加入集合
            list.add(root);

             //System.out.println(list);

        }
        return list.get(0);

    }


}


class Nodes implements Comparable<Nodes>{
    char c;

    int val;//权重

    Nodes left;

    Nodes right;


    public Nodes(int val) {
        this.val = val;
    }

    public void preOrder() {
        System.out.println(this);
        if (this.left != null) this.left.preOrder();
        if (this.right != null) this.right.preOrder();
    }

    @Override
    public String toString() {
        return "Nodes{" +
                "val=" + val +
                '}';
    }

    @Override
    public int compareTo(Nodes o) {
        return this.val - o.val;
    }
}
